package bitetorrent.peersComm;

import bitetorrent.helper.Converter;
import bitetorrent.helper.Helper;
import bitetorrent.model.FileDownloader;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class P2PClient extends P2P {

    public P2PClient(Socket sock, FileDownloader downloader) throws IOException {
        super(sock);
        this.downloader = downloader;
        type = "client";
    }

    @Override
    public void run() {
        try {
            System.out.println("Handshke to " + sock.getInetAddress().getHostAddress());
            if (handshake()) {
                try {
                    System.out.println("handshake sucess from " + sock.getInetAddress().getHostAddress());
                    recieveMessage();
                } catch (InterruptedException ex) {
                    Logger.getLogger(P2PClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                System.out.println("Handshke to " + sock.getInetAddress().getHostAddress() + " gagal. Socket ditutup.");
                sock.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(P2PClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean handshake() throws IOException {

        byte[] len;
        byte[] content;
        byte[] msg;
        StringBuilder sb = new StringBuilder();
        // pstr field
        sb.append("BitTorrent protocol");
        // reserved field
        sb.append("        ");
        // info_hash field
        sb.append(Converter.bytesToString(downloader.torrent.infoHash));
        // Convert to byte
        content = Converter.stringToBytes(sb.toString());
        len = Converter.intToBytes(19);
        // Merge
        msg = Helper.concat(len, content);

        // Debug
        System.out.println("handshake message : " + sb.toString());

        // Write
        out.write(msg);

        return isHandshakeSucces();
    }

    private boolean isHandshakeSucces() throws IOException {
        long timeout = System.currentTimeMillis() + 10000;

        while (System.currentTimeMillis() < timeout) {
            if (in.available() > 0) {
                return true;
            }
        }
        return false;
    }
}
